﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Incendios0_1.Camera.wpfdatamanager;
using System.Configuration;
using System.Collections;
using Emgu.CV;
using Emgu.CV.Structure;
using Incendios0_1.sms;
using Emgu.CV.UI;
using Incendios0_1.Camera;
using AsyncCamera.Camera.Pelco;
using Incendios0_1.tools;
using System.Diagnostics;
using Incendios0_1.user_managment;
using System.ComponentModel;
using System.Threading;
using Incendios0_1.Camera.hplayer;

namespace Incendios0_1
{//http://140.148.67.250/snap.jpg 1 D:\Videos\MVI_0729.AVI
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool? auth;
        private LoadState state;

        private List<StackPanel> displayPanels;

        public MainWindow()
        {
            InitializeComponent();
            DBControler.Initialize();
            auth = false;
            //forceAuthentication();
            if (auth == null || auth == false)
            {
                Incendios0_1.authentication.Window1 authw = new Incendios0_1.authentication.Window1();
                authw.ShowDialog();
                auth = authw.DialogResult;
            }
            if (auth == null || auth == false)
            {
                try
                {
                    this.Close();
                }
                catch (Exception)
                {
                }
            }
            else
            {
                CameraManager.InitializeCameras();
            }
        }

        [Conditional("DEBUG")]
        private void forceAuthentication()
        {
            auth = true;
        }

        private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void cameras_Click(object sender, RoutedEventArgs e)
        {
            CameraListView clw = new CameraListView();
            clw.ShowDialog();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MainGrid.Visibility = System.Windows.Visibility.Hidden;
            CameraManager.InitializeDisplays(Int32.Parse(ConfigurationManager.AppSettings["NumCamerasDisplay"]));
            createMainPanel();
            state = new LoadState(true, 0);
            busyPanel.DataContext = state;
            this.UpdateLayout();
            CameraManager.StartCapture(state, 80);
            SerialPortManager.InitPorts(state, 20);
            state.IsBusy = false;
            MainGrid.Visibility = System.Windows.Visibility.Visible;
        }

        private void createMainPanel()
        {
            displayPanels = new List<StackPanel>();
            int cameras = Int32.Parse(ConfigurationManager.AppSettings["NumCamerasDisplay"]);
            int rows = (int)Math.Floor(Math.Sqrt(cameras));
            int count=0;
            for (int y = 0; y < rows; y++)
            {
                StackPanel p = new StackPanel();
                p.Height = MainGrid.ActualHeight / rows;
                p.Width = MainGrid.ActualWidth;
                p.Background = MainGrid.Background;
                p.Orientation = Orientation.Horizontal;
                DockPanel.SetDock(p, Dock.Top);
                MainGrid.Children.Add(p);
                displayPanels.Add(p);
                
                for(int i = 0; i < (Math.Ceiling(Math.Sqrt(cameras))); i++)
                {
                    if (count<CameraManager.displays.Count)
                    {
                        CameraManager.displays[count].Width = MainGrid.ActualWidth / Math.Ceiling(Math.Sqrt(cameras));
                        CameraManager.displays[count].Height = p.Height;
                        p.Children.Add(CameraManager.displays[count]);
                        CameraManager.displays[count].Display.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(Display_MouseDoubleClick);
                        count++;
                    }
                    else
                        break;
                }
            }
        }

        public static void Display_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            OpenCameraControlPanel(sender);
        }

        public static void OpenCameraControlPanel(object sender)
        {
            if (SerialPortManager.CameraPortOpen)
            {
                try
                {
                    LinkedImageBox<AbstractCamera> item = (LinkedImageBox<AbstractCamera>)sender;
                    AbstractCamera cam = item.Link;
                    CameraData actualCamera = cam.cameraData;
                    if (!(cam is PelcoCamera))
                    {
                        Microsoft.Windows.Controls.MessageBox.Show("La camara no soporta control manual", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                    else if (actualCamera.HWControlAddress != null && actualCamera.HWControlAddress >= 1 && actualCamera.HWControlAddress <= 30)
                    {
                        CameraManualControlW uiCamera = new CameraManualControlW(cam as PelcoCamera);
                        uiCamera.ShowDialog();
                    }
                }
                catch { }
            }
            else
            {
                Microsoft.Windows.Controls.MessageBox.Show("El puerto serial para control de camara no esta disponible", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void actualizeMainPanel()
        {
            if (displayPanels != null)
            {
                int cameras = Int32.Parse(ConfigurationManager.AppSettings["NumCamerasDisplay"]);
                int rows = (int)Math.Floor(Math.Sqrt(cameras));
                foreach (StackPanel pan in displayPanels)
                {
                    pan.Height = (MainGrid.ActualHeight) / rows;
                    pan.Width = MainGrid.ActualWidth; 
                }
                foreach (CameraSink dcc in CameraManager.displays)
                {
                    dcc.Width = MainGrid.ActualWidth / Math.Ceiling(Math.Sqrt(cameras));
                    dcc.Height = (MainGrid.ActualHeight) / rows;
                }
            }
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            actualizeMainPanel();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            CameraManager.StopCapture();
            SerialPortManager.ClosePorts();
            CameraManager.windowMap.Close();
         }

        private void sendMSM_Click(object sender, RoutedEventArgs e)
        {
            if (SerialPortManager.SMSPortOpen)
            {
                SMSWindow clw = new SMSWindow();
                clw.ShowDialog();
            }
            else
            {
                Microsoft.Windows.Controls.MessageBox.Show("El puerto serial para mensajes no esta disponible", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void AddContact_Click(object sender, RoutedEventArgs e)
        {
            new addsmscontact().ShowDialog();
        }

        private void EditContact_Click(object sender, RoutedEventArgs e)
        {
            Contacts contact = new lookfor_contact().Search();
            if (contact != null)
            {
                new addsmscontact(contact).ShowDialog();
            }
        }

        private void DeleteContact_Click(object sender, RoutedEventArgs e)
        {
            new delete_sms_contact().ShowDialog();
        }

        private void addUser_Click(object sender, RoutedEventArgs e)
        {
            new Adduser().ShowDialog();
        }

        private void deleteUser_Click(object sender, RoutedEventArgs e)
        {
            new Window1().ShowDialog();
        }

        private void editUser_Click(object sender, RoutedEventArgs e)
        {
            Tuple<Users,Contacts> user = new lookfor_user().Search();
            if (user != null)
            {
                new Adduser(user.Item1,user.Item2).ShowDialog();
            }
        }

        private void explore_Click(object sender, RoutedEventArgs e)
        {
            new WindowPlayer().Show();
        }

        private void showMap_Click(object sender, RoutedEventArgs e)
        {
            if (CameraManager.WindowMap.IsVisible)
                CameraManager.WindowMap.Hide();
            else
                CameraManager.WindowMap.Show();
        }

        private void about_Click(object sender, RoutedEventArgs e)
        {
            new About().ShowDialog();
        }
    }
}
